package com.vodone.v1pin.detail
{
	import caurina.transitions.Tweener;
	
	import com.vodone.v1pin.detail.events.SendDataEvent;
	import com.vodone.v1pin.detail.events.ZoomEvent;
	import com.vodone.v1pin.detail.vo.ProductDetailVO;
	import com.vodone.v1pin.detail.widgets.AnimationPanel;
	import com.vodone.v1pin.detail.widgets.LeftImage;
	import com.vodone.v1pin.productlist.vo.ProductItemVO;
	import com.vodone.v1pin.userInfo.event.CloseWindowEvent;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.ui.Keyboard;
	import flash.utils.setTimeout;
	
	import mx.binding.utils.BindingUtils;
	import mx.containers.Canvas;
	import mx.controls.Button;
	import mx.controls.Image;
	import mx.core.Application;
	import mx.core.FlexGlobals;
	import mx.effects.Fade;
	import mx.events.EffectEvent;
	import mx.events.FlexEvent;
	import mx.events.ResizeEvent;
	
	
	
	[Event(name="close")]
	public class ProductDetailPanel extends Canvas
	{
		public var isCreation:Boolean = false;
		
		public function ProductDetailPanel()
		{
			super();
			this.percentHeight = 100;
			this.percentWidth = 100;
			this.verticalScrollPolicy = "off";
			this.horizontalScrollPolicy = "off";
			this.setStyle("backgroundAlpha",0.01);
			this.setStyle("backgroundColor",0);
			
			addEventListener( FlexEvent.CONTENT_CREATION_COMPLETE , creationCompleteHandler );
			addEventListener( Event.ADDED_TO_STAGE , addHandler );
			addEventListener( Event.REMOVED_FROM_STAGE , removeHandler );
			addEventListener(  ResizeEvent.RESIZE  , resizeHandler );
			
		}
		
		protected function creationCompleteHandler(event:FlexEvent):void
		{
			isCreation = true;
		}
		
		private function mykeydownHandler(e:KeyboardEvent):void
		{
			var pos:Number = verticalScrollPosition;
			switch(e.keyCode)
			{
				case Keyboard.LEFT:
					gotoPre();
					break;
				case Keyboard.RIGHT:
					gotoNext();
					break;
			}
		}
		
		public function addListeners():void
		{
			if( stage ){
				systemManager.addEventListener(MouseEvent.MOUSE_WHEEL , mouseWheelHandler );
				stage.addEventListener( KeyboardEvent.KEY_DOWN , mykeydownHandler );
			}
		}
		public function removeListeners():void
		{
			if( stage ){
				systemManager.removeEventListener( MouseEvent.MOUSE_WHEEL , mouseWheelHandler );
				stage.removeEventListener( KeyboardEvent.KEY_DOWN , mykeydownHandler );
			}
		}
		private function addHandler(e:Event):void
		{
			addListeners();
			detailView.gotoFirstTab();
		}
		
		private function removeHandler(e:Event):void
		{
//			new CloseWindowEvent(CloseWindowEvent.CLEAR_EVENT).dispatch();
			if( detailView && detailView.mainContent && detailView.mainContent.mainImage && detailView.mainContent.mainImage.img){
				detailView.mainContent.mainImage.img.clear();
			}
			if( detailView && detailView.rightView1 ){
//				detailView.rightView1.detailVO = new ProductDetailVO();
			}
			removeListeners();
		}
		
		private function mouseWheelHandler(e:MouseEvent):void
		{
			if( e.delta < 0 )
			{
				gotoNext();
			}
			else
			{
				gotoPre();
			}
		}
		private function gotoPre():void
		{
			if( isLR ) return;
			var item:ProductItemVO = getPreProduct();
			if( null != item )
			{
				var id:String = item.productId;
				playAnimation1("pre",id);
			}
		}
		private function gotoNext():void
		{
			if( isLR ) return;
			var item:ProductItemVO = getNextProudct();
			if( null != item )
			{
				var id:String = item.productId;
				playAnimation1("next",id);
			}
		}
		
		private var centerX:int;
		private var centerY:int;
		private var image:Image = new Image();
		private function playAnimation1(str:String = "",id:String = ""):void
		{
			var bitmap:BitmapData = new BitmapData(detailView.width,detailView.height);
			bitmap.draw(detailView);
			image.mouseEnabled = false;
			image.source = new Bitmap(bitmap);
			image.x = detailView.x;
			image.y = detailView.y;
			centerX = detailView.x;
			centerY = detailView.y;
			detailView.setStyle( "verticalCenter" , null );
			detailView.setStyle( "horizontalCenter" , null );
			this.addChild(image);
			detailView.clear();
			productId = id;
			isLR = true;
			
			if( str == "pre" ){
				detailView.x = -detailView.width;
				Tweener.addTween( image,{x:this.width,time:.7,transition:"easeOutQuint",onComplete:endEffectImageLR} );
			}else{
				detailView.x = this.width;
				Tweener.addTween( image,{x:-detailView.width,time:.7,transition:"easeOutQuint",onComplete:endEffectImageLR} );
			}
			Tweener.addTween( detailView,{x:centerX,time:.7,transition:"easeOutQuint",onComplete:endDetailEffectLR} );
		}
		
		private var isLR:Boolean = false;
		private function endEffectImageLR():void
		{
			if(image && this.getChildIndex(image) > 0 ){
				this.removeChild(image);
			}
		}
		
		private function endDetailEffectLR():void
		{
			isLR = false;
			detailView.setStyle( "verticalCenter" , 0 );
			detailView.setStyle( "horizontalCenter" , 0 );
		}
		
		public var detailView:ProductDetailView;
		private var zoomView:BigImageContent;
		
		public var productList:Array = [];
		
		
		private var productIdDirty:Boolean = false;
		private var _productId:String = "";
		[Bindable]
		public function get productId():String
		{
			return _productId;
		}
		public function set productId(value:String):void
		{
//			if(value == "") {
//				return;
//			}
			_productId = value;
			productIdDirty = true;
			invalidateProperties();
		}
		protected override function commitProperties():void
		{
			super.commitProperties();
			if( productIdDirty )
			{
				productIdDirty = true;
				setNextAndPre();
//				if( whiteBoard )
//				{
//					playAnimation();
//				}
			}
		}
		private var nextImage:LeftImage = new LeftImage();
		private var preImage:LeftImage = new LeftImage();
		
		public function refresh():void
		{
			var id:String = productId;
			productId = "";
			productId = id;
		}
		
		private function setNextAndPre():void
		{
			var nextProduct:ProductItemVO = getNextProudct();
			var preProduct:ProductItemVO = getPreProduct();
			if( preProduct )
			{
				nextImage.item = preProduct;
				nextImage.visible = true;
			}
			else
			{
				nextImage.visible = false;	
			}
			if( nextProduct )
			{
				preImage.item = nextProduct;
				preImage.visible = true;
			}
			else
			{
				preImage.visible = false;
			}
		}
		
		
		
		private function changeIdHandler( e:SendDataEvent ):void
		{
			this.productId = e.data["id"];
		}
		
		private function zoomHandler( event:ZoomEvent ):void
		{
			zoomView.imageInfo = event.data;
			zoomView.detailVO = event.detailVO;
			zoomView.obj = event.obj;
			zoomView.visible = true;
		}
		
		private function zoomHandler1( event:ZoomEvent ):void
		{
			if(detailView && detailView.mainContent && detailView.mainContent.mainImage){
				detailView.mainContent.mainImage.imageInfo = event.data;
			}
		}
		
		override protected function createChildren():void
		{
			super.createChildren();
			detailView = new ProductDetailView();
			BindingUtils.bindProperty( detailView , "productId" , this , "productId" );
			detailView.setStyle( "verticalCenter" , 0 );
			detailView.setStyle( "horizontalCenter" , 0 );
			detailView.addEventListener( SendDataEvent.SEND_DATA_Event , changeIdHandler );
			detailView.addEventListener( ZoomEvent.ZOOM_EVENT ,zoomHandler );
			detailView.addEventListener( "seeRecommend" , seeRecommendHandler );
			detailView.addEventListener( "close" , closeHandler); 
			addChild( detailView );
			
			
			
			
			
			nextImage.isRight = false;
			nextImage.setStyle("verticalCenter", 0);
			
			nextImage.addEventListener( MouseEvent.CLICK , imageClickHandler );
			addChild( nextImage );
			
			nextImage.isRight = true;
			preImage.setStyle("verticalCenter", 0);
			
			preImage.addEventListener( MouseEvent.CLICK , imageClickHandler );
			addChild( preImage );
			setLeftImage();
			addWhiteBoard();
			
			
			zoomView = new BigImageContent();
			zoomView.addEventListener( ZoomEvent.ZOOM_EVENT ,zoomHandler1 );
			zoomView.visible = false;
			addChild(zoomView);
			
//			addAPanel();
		}
		private function resizeHandler( e:ResizeEvent ):void
		{
			setLeftImage();
		}
		
		private function setLeftImage():void
		{
			var left:Number =  ((FlexGlobals.topLevelApplication as Application).width - detailView.width)/2 - 300 - 15;
			nextImage.setStyle("left", left);
			preImage.setStyle("right", left);
		}
		
		private var isRecommend:Boolean = false;
		private var mainId:String = null;
		private function seeRecommendHandler(e:SendDataEvent):void
		{
			isRecommend = true;
			mainId = this.productId;
			this.productId = e.data["id"];
			
		}
		
		private function closeHandler( e:Event ):void
		{
			if( isRecommend )
			{
				isRecommend = false;
				productId = mainId;
				e.stopImmediatePropagation();
			}
			else
			{
				productList = [];
			}
		}
		
		private var whiteBoard:Canvas;
		private function addWhiteBoard():void
		{
			whiteBoard = new Canvas();
			whiteBoard.mouseEnabled = false;
			whiteBoard.width = detailView.width;
			whiteBoard.height = detailView.height;
			whiteBoard.alpha = 0;
			whiteBoard.setStyle( "backgroundColor" , 0xffffff);
			whiteBoard.setStyle( "verticalCenter" , 0 );
			whiteBoard.setStyle( "horizontalCenter" , 0 );
			
			addChild(whiteBoard);
			addAPanel();
		}
		
		private var aniPanel:AnimationPanel;
		private function addAPanel():void
		{
			aniPanel = new AnimationPanel();
			aniPanel.setStyle("verticalCenter",0);
			addChild( aniPanel );
		}
		
		
		
		private function playAnimation():void
		{
			var fade:Fade = new Fade();
			fade.alphaTo = 1;
			fade.target = whiteBoard;
			fade.duration = 500;
			fade.addEventListener(EffectEvent.EFFECT_END , fadeEndHandler );
			fade.play()
				
			aniPanel.showMe();
		}
		private function fadeEndHandler(e:Event):void
		{
			var fade:Fade = new Fade();
			fade.alphaTo = 0;
			fade.target = whiteBoard;
			fade.duration = 500;
			fade.play();
		}
		
		
		private function imageClickHandler( e:MouseEvent ):void
		{
			var target:LeftImage = e.currentTarget as LeftImage;
			var actTarget:LeftImage = target == preImage ?  preImage : nextImage ;
			if(target == preImage){
				gotoNext();
			}else{
				gotoPre();
			}
//			this.productId = actTarget.item.productId;
		}
		private function getNextProudct():ProductItemVO
		{
			if( productList && productList.length > 1 )
			{
				var index:int = getCurrentIndex();
				if( index < 0 || index >= productList.length - 1 ) return null;
				var nextIndex:int = ( index + 1 ) % ( productList.length );
				return productList[ nextIndex ] as ProductItemVO;
			}
			return null;
		}
		private function getPreProduct():ProductItemVO
		{
			if( productList &&  productList.length > 1 )
			{
				var index:int = getCurrentIndex();
				if( index <= 0 ) return null;
				var preIndex:int = ( index - 1 + productList.length ) % ( productList.length  );
				return productList[ preIndex ] as ProductItemVO;
			}
			return null;
		}
		private function getCurrentIndex():int
		{
			for( var i:int = 0 ; i < productList.length ; i++ )
			{
				var item:ProductItemVO = productList[i] as ProductItemVO;
				if( item.productId == productId )
				{
					return i;
				}
			}
			return -1;
		}
		
		
		
		protected override function updateDisplayList(w:Number, h:Number):void
		{
			super.updateDisplayList( w , h );
		}
	}
}